import os
from typing import List
import pandas as pd
from flask import request, send_from_directory
from dash import get_app
from dash import (
    html,
    callback,
    Output,
    Input,
    State,
    register_page,
)

from ddbtools import (
    BaseCRUD,
    Filter,
    Comparator,
    DBDf,
    create_db,
    create_table,
    DbColumn,
    get_all_dbs,
    get_all_tables,
    get_table_info,
    get_table_columns,
)
from gypb.db import get_db
from gypb.component import DFTable
import feffery_antd_components as fac

app = get_app()
register_page(__name__, name="净值查询", order=4)

layout = html.Div(
    [
        fac.AntdText("产品代码"),
        fac.AntdSelect(
            id="nvquery-select-by-prodcode",
            placeholder="请输入产品代码",
            mode="multiple",
            options=[],
            autoSpin=True,
            debounceWait=800,
            style={"width": "600px"},
        ),
        fac.AntdText("\n日期范围"),
        fac.AntdDateRangePicker(
            id="nvquery-date-range-picker",
        ),
        fac.AntdButton("查询", id="nvquery-button", type="primary"),
        fac.AntdDivider(),
        html.Div(id="netvalue-query-table"),
    ]
)


@callback(
    Output("nvquery-date-range-picker-output", "children"),
    Input("nvquery-date-range-picker", "value"),
)
def netvalue_query(value: List[str]):
    return f"value: {value}"


@callback(
    Output("nvquery-select-by-prodcode", "options"),
    Input(
        "nvquery-select-by-prodcode",
        "debounceSearchValue",
    ),
)
def select_auto_spin_remote_load_options_demo(debounceSearchValue):
    if debounceSearchValue:
        crud = BaseCRUD("dfs://infos", "hfn_product")
        with get_db() as session:
            prods = crud.get(
                session,
                conds=[Filter("fund_short_name", Comparator.like, debounceSearchValue)],
            )
        options = [
            {
                "value": f"{prod.get('register_number')}-{prod.get('fund_short_name')}",
                "label": f"{prod.get('register_number')}-{prod.get('fund_short_name')}",
            }
            for prod in prods.to_dict("records")[:50]
        ]
        return options


@callback(
    Output("netvalue-query-table", "children"),
    Input("nvquery-button", "nClicks"),
    State("nvquery-select-by-prodcode", "value"),
    State("nvquery-date-range-picker", "value"),
)
def netvalue_query(nClicks, codes, date_range):
    if nClicks:
        codes = {code.split("-")[0]: code.split("-")[1] for code in codes}
        start, end = pd.to_datetime(date_range)
        crud = BaseCRUD("dfs://product_daily", "attr_double")
        with get_db() as session:
            nv_data = crud.get(
                session,
                conds=[
                    Filter("code", Comparator.isin, list(codes.keys())),
                    Filter("datetime", Comparator.gt, start),
                    Filter("datetime", Comparator.lt, end),
                    Filter("attribute", Comparator.isin, ["netvalue", "cum_netvalue"]),
                ],
            ).reset_index()
        nv_data["fund_name"] = nv_data["code"].map(codes)
        nv_data.rename(
            columns={
                "datetime": "日期",
                "code": "产品代码",
                "netvalue": "单位净值",
                "cum_netvalue": "累计净值",
                "fund_name": "产品简称",
            },
            inplace=True,
        )
        nv_data = nv_data[["日期", "产品简称", "产品代码", "单位净值", "累计净值"]].sort_values("日期")

        table = DFTable(
            df=nv_data,
            name = "table-netvalue-query",
            downloadable=True,
            mode="client-side",
            )
        return table.layout
        # table = fac.AntdTable(
        #     id="table-netvalue-query",
        #     columns=[
        #         (
        #             {"title": c, "dataIndex": c, "editable": False}
        #             if c == "项目名称"
        #             else {"title": c, "dataIndex": c, "editable": True}
        #         )
        #         for c in nv_data.columns
        #     ],
        #     data=nv_data.to_dict("records"),
        # )
        # return table
